<?php
declare(strict_types=1);

namespace app\controller\index;

use app\BaseController;
use app\result\UserResult;
use think\App;
use think\facade\Route;

class BaseIndex extends BaseController
{
    protected $objResult;
    protected $user_id;
    protected $user_code;
    protected $token;
    protected $unauthorized = [];//不需要token验证的接口

    protected $param = [];


    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->param = request()->filter('trim,htmlspecialchars')->param();
        $this->check_token();
    }

    public function check_token()
    {
        $this->token = request()->header('authorization');

        $dispatch = (Route::check())->getDispatch();
        $action = $dispatch[1] ?? null;
        $controller = $dispatch[0] ?? null;
        if ($this->token || !in_array('*', $this->unauthorized) && !$this->user_id) {
            if ($this->token && stripos($this->token, 'Bearer') !== 0) {
                data_return('token格式错误', 401);
            }
            if ($this->token) {
                //Bearer
                $this->token = trim(str_replace('Bearer', '', $this->token));
            }

            if (!empty($this->token)) {
                $userCheck = (new UserResult())->get_token_user($this->token, 'user_id,user_code');
                if ($userCheck['code'] == 0) {
                    $user = $userCheck['data'];
                    if ($user) {
                        $this->user_code = $user['user_code'];
                        $this->user_id = $user['user_id'];
                    }
                }
            }
            if ($action && !in_array($action, $this->unauthorized) && !$this->user_id) {
                data_return('登录过期，请重新登录', 401, $userCheck ?? null);
            }
        }
    }
}
